<template>
  <div>
    <el-card class="box-card">
      <el-button type="primary" style="margin: 0 0 20px" @click="isShow">提交</el-button>
      <el-table :data="trademarkList" border style="width: 100%">
        <el-button type="primary">主要按钮</el-button>
        <el-table-column type="index" align="center" label="序号" width="60" />
        <el-table-column prop="tmName" align="center" label="品牌名称" width="180" />
        <el-table-column prop="name" label="品牌LOGO" width="180">
          <template v-slot="{ row }">
            <img :src="row.logoUrl" :alt="row.tmName" style="width: 100px" />
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template v-slot="{ row }">
            <el-button class="el-icon-edit" type="warning" @click="showUpdateDialog(row.id)">修改</el-button>
            <el-button class="el-icon-delete" type="danger" @click="delOneTrademark(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--   current-page: 表示当前是第几页
        total: 表示的是总条数 也就是数据的总数量
        page-size: 每页需要显示的数量
        page-sizes: 表示一共有多少页
        pager-count: 表示连贯的页码数量  相当于是之前的continues  -->
      <el-pagination :total="total" :current-page="currentPage" :page-sizes="[3, 5, 10]" :page-size="limit" layout="prev, pager, next, jumper, ->, sizes, total " @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>
    <!-- 对话框 -->
    <el-dialog title="添加品牌" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="tmfrom" :model="tmfrom">
        <el-form-item label="品牌名称" :label-width="formLabelWidth" prop="tmName">
          <el-input autocomplete="off" v-model="tmfrom.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" :label-width="formLabelWidth" prop="logoUrl">
          <el-upload class="avatar-uploader" action="/dev-api/admin/product/fileUpload" :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" accept=".jpg,.jpeg,.png ">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon" />
            <div class="el-upload__tip" slot="tip">只能上传jpg/png/jpeg文件,且不超过2M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdateOneTrademark">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { reqGetTrademarkList, reqAddOneTrademark, reqDelOneTrademark, reqGetOneTrademark, reqUpdateOneTrademark } from '@/api/product/index'
export default {
  name: 'Trademark',
  data() {
    return {
      currentPage: 1, // 当前页码
      limit: 5, // 每页要显示的商品数
      trademarkList: [], // 请求回来的商品
      total: 0, // 总的商品条数
      imageUrl: '',
      dialogFormVisible: false, // 是否弹出对话框的标识
      formLabelWidth: '100px',
      tmfrom: {
        tmName: '',
        logoUrl: ''
      },
      rules: {
        tmName: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 6, message: '长度在 2 到 6 个字符', trigger: 'blur' }
        ],
        logoUrl: [{ required: true, message: '请选择一张图片', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.getTrademarkList()
  },
  methods: {
    //获取当前品牌数据列表
    async getTrademarkList() {
      const { currentPage: page, limit } = this
      const result = await reqGetTrademarkList(page, limit)
      // console.log(result);
      if (result.code === 200) {
        this.total = result.data.total
        this.trademarkList = result.data.records
      } else {
        this.$message.error('获取数据列表失败')
      }
    },
    //分页方法
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.limit = val
      this.currentPage = 1
      this.getTrademarkList()
    },
    //分页方法
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val
      this.getTrademarkList()
    },
    //提交显示对话框
    isShow() {
      this.tmfrom.tmName = ''
      this.imageUrl = ''
      this.dialogFormVisible = true
    },
    //上传成功之后调用
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.tmfrom.logoUrl = res.data //上传成功之后的图片地址储存在这里
      //上传图片成功之后,移除校验提示
      this.$refs.tmfrom.clearValidate('logoUrl')
    },
    //上传之前调用
    beforeAvatarUpload(file) {
      // const isJPG = file.type === 'image/jpeg,image/jpg'
      const imgArr = ['image/jpeg', 'image/jpg', 'image/png']
      const isJPG = imgArr.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //添加一个或更新一个品牌数据
    addOrUpdateOneTrademark() {
      this.$refs['tmfrom'].validate(async (valid) => {
        if (valid) {
          let result
          if (this.tmfrom.id) {
            result = await reqUpdateOneTrademark(this.tmfrom)
          } else {
            result = await reqAddOneTrademark(this.tmfrom)
          }

          if (result.code === 200) {
            this.dialogFormVisible = false

            this.$message('操作成功')
            this.getTrademarkList()
          } else {
            this.$message.error('操作失败')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    //删除一条
    delOneTrademark(id) {
      // console.log(id)
      this.$confirm('你真的要删除此数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let result = await reqDelOneTrademark(id)
          if (result.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.currentPage = this.trademarkList.length === 1 ? this.currentPage - 1 : this.currentPage
            this.getTrademarkList()
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //根据id更新修改数据
    async showUpdateDialog(id) {
      let result = await reqGetOneTrademark(id)
      if (result.code === 200) {
        this.dialogFormVisible = true
        this.tmfrom = result.data // 更新待渲染的数据
        this.imageUrl = result.data.logoUrl
      }
    }
  }
}
</script>

<style lang="" scoped></style>
